import 'dart:async';

import 'package:flutter/material.dart';
import '../wigets/friend-group.dart';
import 'package:my_chat/static-test-data/friend-list.dart';

class AddressBook extends StatelessWidget {
  GlobalKey<State<ContactListScreen>> controller = GlobalKey();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // RenderBox? renderBox = controller.currentContext?.findRenderObject() as RenderBox;
          // print(renderBox?.size);
          FriendGroup v = (controller?.currentState as ListState).renderMap['A']!.currentWidget as FriendGroup;
          PosAndSize posAndSize = v.getLetterPositionAndSize();

          print('${posAndSize.offset} ${posAndSize.size}');
  
        },
        child: Text("按钮"),
      ),
      appBar: AppBar(
        title: Text("通讯录"),
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.only(bottom: 50),
        child: Stack(
          children: [ContactListScreen(key: controller)],
        ),
      ),
    );
  }
}

class ContactListScreen extends StatefulWidget {
  const ContactListScreen({super.key});

  @override
  State<StatefulWidget> createState() {
    return ListState();
  }
}

class ListState extends State<ContactListScreen> {
  Map<String, GlobalKey> renderMap = {};

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      // physics: const NeverScrollableScrollPhysics(),
      slivers: [
        SliverPersistentHeader(
          delegate: _StickyHeaderDelegate(),
          pinned: true,
        ),
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              GlobalKey globalKey = GlobalKey ();
              List<String> keys = listMap.keys.toList();
              String key = keys[index];
              renderMap[key] = globalKey;
              return FriendGroup(key: globalKey, entry: MapEntry(key, listMap[key]!));
            },
            childCount: listMap.length,
          ),
        ),
      ],
    );
  }
}

// 粘性头部委托
class _StickyHeaderDelegate extends SliverPersistentHeaderDelegate {
  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    // 这里可以自定义你的头部内容
    return Container(
      height: 30,
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.only(left: 10.0),
      color: Colors.grey[200],
      child: const Text(
        '字母栏',
        style: TextStyle(
          fontSize: 14,
        ),
      ),
    );
  }

  @override
  double get maxExtent => 30; // 头部最大高度

  @override
  double get minExtent => 30; // 头部最小高度（通常与最大高度相同以实现固定高度）

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
      false;
}
